package chapter5.lessons.udpDemo01;

import java.io.IOException;
import java.net.*;

/**
 * @Project ：learn_java
 * @File ：SendMessageDemo01.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/12 17:24
 * @Description ：UDP发送数据案例，向指定端口发送字符信息
 */

public class SendMessageDemo01 {
    public static void main(String[] args) throws SocketException, UnknownHostException {

        // 空参：随机从端口中选取一个
        DatagramSocket ds = new DatagramSocket();

        // 发送的内容
        String str = "我是发送的东西";

        byte[] bytes = str.getBytes();

        InetAddress address = InetAddress.getByName("127.0.0.1");

        int port = 10086;

        DatagramPacket dp = new DatagramPacket(bytes, bytes.length, address, port);

        // 发送数据
        try {
            ds.send(dp);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 释放资源
        ds.close();
    }
}
